/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-10-29
 * Time: 22:56
 */
public class Solution {
    public static int maxSideLength(int[][] mat, int threshold) {
        int row = mat.length;
        int col = mat[0].length;
        int[][] dp = new int[row+1][col+1];
        // 二维前缀和
        for (int i = 1; i <= row; i++) {
            for (int j = 1; j <= col; j++) {
                dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + mat[i-1][j-1];
            }
        }
        // 求出二分的边界值
        int min = Math.min(row, col);
        int left = 0;
        int right = min;
        while (left < right) {
            int mid = ((right-left + 1) >> 1) + left;
            boolean flag = false;
            // 下标表示正方形左上角那个位置

            // 一定注意这个是 从 [0,0] 开始的
            for (int i = 0; i + mid <= row; i++) {
                for (int j = 0; j + mid <= col; j++) {
                    int sum = dp[i+mid][j+mid] - dp[i+mid][j] - dp[i][j+mid] + dp[i][j];
                    // 只要在这个边长的条件下有满足条件的那么就跳出循环即可
                    if (sum <= threshold) {
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    break;
                }
            }
            if (!flag) {
                right = mid - 1;
            } else {
                left = mid;
            }
        }
        return right;
    }
}
